package com.jd.controller;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    // 设置过滤器的类型：pre、post
    @Override
    public String filterType() {
        return "pre";
    }


    // filter的执行顺序，数字越小，执行时机越高
    @Override
    public int filterOrder() {
        return 0;
    }


    // 是否执行run方法，true：执行/false：不执行
    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        // 2.判断请求路径是否以login/register结尾
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }

        return true;
    }


    // 此自定义filter的核心业务方法执行
    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 1.获取到请求头
        RequestContext currentContext = RequestContext.getCurrentContext();
        String token = currentContext.getRequest().getHeader("token");

        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");

        // 2.判断是否包含token
        if (StringUtils.isEmpty(token)){
            // 设置响应内容
            PrintWriter writer = response.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","登录校验失败，请重新登录！");
            map.put("obj","noLogin");
            String jsonString = JSONObject.toJSONString(map);
            writer.write(jsonString);

            // 阻止后续filter执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }

        return null;
    }
}
